﻿using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;

namespace OrzRefectorMenu.AssignUserControl
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class Assign : UserControl
    {
        public Assign()
        {
            InitializeComponent();
            textTemplateComboBox.SelectedIndex = 0;
        }

        private void GenerateButton_Click(object sender, RoutedEventArgs e)
        {
            string cmd = textTemplateComboBox.Text;
            string s = string.Empty;
            List<string> properties = new List<string>();

            if (IsObjectCheckBox.IsChecked.Value)
            {
                properties = ParseInput(new TextRange(inputRichTextBox.Document.ContentStart, inputRichTextBox.Document.ContentEnd).Text);
            }
            else
            {
                string text =
                    new TextRange(inputRichTextBox.Document.ContentStart, inputRichTextBox.Document.ContentEnd).Text;
                using (StringReader reader = new StringReader(text))
                {
                    string line;
                    while ((line = reader.ReadLine()) != null)
                    {
                        properties.Add(line);
                    }
                }
            }

            foreach (var prop in properties)
            {
                var result = cmd.Replace("$A$", ProcessKey("$A$", prop));
                result = result.Replace("$LA$", ProcessKey("$LA$", prop));
                s += result + "\n";
            }
            outputRichTextBox.Document.Blocks.Clear();
            outputRichTextBox.AppendText(s);
            Clipboard.SetText(s);
        }

        List<string> ParseInput(string rawData)
        {
            Regex regex = new Regex(@"(?<=\w+\s)\w+(?=;\n?)");
            var results = regex.Matches(rawData);
            return (results.Cast<Match>().Select(v => v.ToString())).ToList();
        }

        string ProcessKey(string key, string prop)
        {
            if ("$A$" == key)
            {
                return prop;
            }
            else if ("$LA$" == key && !string.IsNullOrEmpty(prop))
            {
                char[] letters = prop.ToCharArray();
                letters[0] = char.ToLower(letters[0]);
                return new string(letters);
            }
            else
            {
                return string.Empty;
            }
        }


    }


}
